<template>
  <div class="ocrContent">
    <el-card>
      <el-page-header @back="router.back()">
        <template #content>
          <span class="text-large font-600 mr-3" style="color: #fff;"> {{ route.query.title }} </span>
        </template>
      </el-page-header>
    </el-card>
    <div class="ocrMain">
      <el-card style="background: black;">
        <div class="content">
          <div class="left">
            <el-form label-width="100px">
              <el-form-item label="图片地址：" prop="content">
                <el-input show-word-limit v-model="ocrBefore" placeholder="手动输入图片地址" maxlength="1024" style="width: 90%;height: 40px;" :disabled="imgFile != ''" />
              </el-form-item>
              <el-form-item label="所选图片：" prop="content" style="margin-top: 20px;">
                <div class="imgDefault" v-if="!imgFile" @click.stop="imgMessage">
                  <el-icon style="width: 100%;height: 100%;color: rgba(238, 238, 238, 0.8);font-weight: 100;font-size: 70px;">
                    <Plus style="border: none;" />
                  </el-icon>
                </div>
                <img :src="`data:image/png;base64,${imgFile}`" style="width: 90%;height: auto;" alt="" v-else>
              </el-form-item>
              <el-form-item
                :prop="imgFile"
                style="margin-top: 5px;"
              >
                <el-upload
                  ref="upload"
                  action="#"
                  :http-request="PTuploadHttpRequest"
                  :show-file-list="false"
                  class="upload-demo"
                  multiple
                  :limit="1"
                  :on-exceed="PThandleExceed"
                >
                  <el-button icon="CameraFilled" class="upload-demo-btn" type="primary">{{ imgFile == '' ? '点此选择图片' : '点此重新上传' }}</el-button>
                </el-upload>
              </el-form-item>
              <el-form-item style="width: 92%;margin-top: 50px;display: flex;">
                <el-button type="primary" style="flex: 1;height: 50px;border-radius: 8px;font-size: 16px;" @click="onturn">
                  开始扫描
                </el-button>
                <el-button type="danger" style="width: 150px;height: 50px;border-radius: 8px;font-size: 16px;" @click="clean">
                  重置
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="right">
            <el-form>
              <el-form-item label="" prop="content" label-width="5px">
                <el-input show-word-limit v-model="ocrAfter" placeholder="请输入内容后进行等待" type="textarea" disabled />
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import Tesseract from 'tesseract.js'
import type { UploadProps, UploadRawFile } from 'element-plus'
import { Plus } from '@element-plus/icons-vue';
import { getBase64 } from '@/utils/plugins'


const route = useRoute()
const router = useRouter()

const ocrBefore = ref<string>('')
const imgFile = ref<any>('')
const ocrAfter = ref<string>('')

const onturn = () => {
  if (ocrBefore.value == '' && imgFile.value == '') {
    ElMessage({
      type: 'warning',
      message: '请选择图片或输入图片地址！'
    })
  } else {
    ElMessageBox.confirm('如果图片地址不正确或图片无文字内容可能无法识别，确定要开始扫描吗？', '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    showClose: false,
    closeOnClickModal: false,
  })
    .then(() => {
      window.showGlobalLoading()
      // recognize 第一个参数：图像，第二个：语种
      // const url = 'https://tesseract.projectnaptha.com/img/eng_bw.png'
      let url
      if (ocrBefore.value) {
        url = ocrBefore.value
      } else {
        url = `data:image/png;base64,${imgFile.value}`
      }
      console.log('url', url)
      Tesseract.recognize(
        url,
        'chi_sim+eng+jpn+spa',
      // { logger: m => console.log(m) }
      ).then((d) => {
        ocrAfter.value = d.data.text
        window.hideGlobalLoading()
      })
        .catch((err: any) => {
          ElMessage({
            type: 'error',
            message: err
          })
        })
    })
  }
}

// import { createWorker } from 'tesseract.js';

// const worker = createWorker({
//   logger: m => console.log(m)
// });

// (async () => {
//   await worker.load();
//   await worker.loadLanguage('eng');
//   await worker.initialize('eng');
//   const { data: { text } } = await worker.recognize('https://tesseract.projectnaptha.com/img/eng_bw.png');
//   console.log(text);
//   await worker.terminate();
// })();

const clean = () => {
  ocrBefore.value = ''
  imgFile.value = ''
  ocrAfter.value = ''
}

const imgMessage = () => {
  ElMessage({
    type: 'warning',
    message: '该区域仅为展示区域，上传图片请点击下方按钮操作！'
  })
}

// 首次上传
const PTuploadHttpRequest = (data: any) => {
  if (ocrBefore.value != '') {
    ElMessage.warning('手动输入后无需上传文件！')
    return
  }
  console.log('data', data)
  if (data.file.type !== 'image/png' && data.file.type !== 'image/jpeg') {
    imgFile.value == ''
    ElMessage.error('请选择格式为jpg或者png类型的图片文件')
    return
  }
  getBase64(data.file).then((res: any) => {
    imgFile.value = data.file.name
    const img_url = res.split(',')[1]
    imgFile.value = img_url
    console.log('imgFile.value', imgFile.value)
  })
}

// 重复上传
const PThandleExceed: UploadProps['onExceed'] = (files: any) => {
  if (ocrBefore.value != '') {
    ElMessage.warning('手动输入后无需上传文件！')
    return
  }
  const file = files[0] as UploadRawFile
  console.log('file', file)
  if (file.type !== 'image/png' && file.type !== 'image/jpeg') {
    imgFile.value == ''
    ElMessage.error('请选择格式为jpg或者png类型的图片文件')
    return
  }
  getBase64(file).then((res: any) => {
    imgFile.value = file.name
    const img_url = res.split(',')[1]
    imgFile.value = img_url
    console.log('form.value.ios_ptFile', imgFile.value)
  })
}

onMounted(() => {

})

</script>

<style lang="scss" scoped>
.ocrContent {
  width: 100%;

  .el-card {
    border-radius: $base-card-border-radius;
  }

  .ocrMain {
    margin-top: 20px;
    padding: 20px;

    .el-card {
      border-radius: 16px;
      box-shadow: 0px 4px 18px 0px rgba(248,216,82, 0.9);

      .content {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: row;

        .left {
          flex: 1.5;
          padding: 10px;
          padding-left: 20px;
          
          .imgDefault {
            width: 90%;
            height: 200px;
            border: 1px dashed #eeeeee;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
          }
          .imgDefault :hover {
              border: 1px dashed rgba(248,216,82, 0.9);;
              color: rgba(248,216,82, 0.9);
            }
          .upload-demo {
            display: block;
            width: 90%;
            height: 55px;
            line-height: 55px;
            text-align: center;
            font-size: 14px;
            background: rgb(248,216,82);
            color: white;
            border-radius: 5px;
          }
          .upload-demo-btn {
            width: 90%;
            height: 55px;
            line-height: 55px;
            background: rgb(248,216,82);
            border: rgb(248,216,82);
            color: #c57c43;
            text-align: center;
            font-size: 18px;
            border-radius: 5px;
          }
          
        }

        .right {
          flex: 1;
          padding: 10px;
          padding-right: 20px;

          :deep(.el-textarea__inner) {
            width: 100%;
            height: 55vh;
            border-radius: 8px;
          }
        }
      }
    }
  }

}
</style>